package com.laber.controller;

import com.laber.domain.Article;
import com.laber.domain.PageResult;
import com.laber.service.ArticleService;
import com.laber.domain.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    //交给登录拦截器进行token验证处理
//    @GetMapping("/list")
//    public Result<String> list(@RequestHeader(name = "Authorization") String token, HttpServletResponse response) {
//        //验证token
//        try {
//            Map<String, Object> clamis = JwtUtil.parseToken(token);
//            return Result.success("所有的文章数据");
//        } catch (Exception e) {
//            //http响应状态码为401
//            response.setStatus(401);
//            return Result.error("未登录");
//        }
//    }

//    @GetMapping("/list")
//    public Result<String> list() {
//        return Result.success("所有的文章数据");
//    }

    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success("添加成功");
    }

    @GetMapping
    public Result<PageResult<Article>> list(
            Integer pageNum, Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state)
    {
        PageResult<Article> pageResult = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pageResult);
    }

    @PostMapping("/updateArticle")
    public Result update(@RequestBody @Validated Article article) {
        articleService.update(article);
        return Result.success("修改成功");
    }

    @DeleteMapping
    public Result delete(Integer id) {
        articleService.delete(id);
        return Result.success("删除成功");
    }
}
